import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hello_flutter/util/PATClient.dart';
import 'package:hello_flutter/util/TFSClient.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppData extends ChangeNotifier {
  String collectionUrl;
  String projectName;

  String _reprter;

  String get reporter => _reprter;

  set reporter(String v) {
    _reprter = v;
    notifyListeners();
  }

  int _days;

  int get days => _days;

  set days(int v) {
    _days = v;
    notifyListeners();
  }

  //PAT
  String _userPAT;

  String get userPAT => _userPAT;

  set userPAT(String value) {
    _userPAT = value;
    SharedPreferences.getInstance()
        .then((pref) => {pref.setString('pat', _userPAT)});
    notifyListeners();
  }

  dynamic _userIdentity;

  set userIdentify(dynamic v) {
    _userIdentity = v;
    notifyListeners();
  }

  dynamic get userIdentify => _userIdentity;

  void offline() {
    this.userPAT = '';
  }

  Future<bool> refresh() async {
    await this._refreshUser();
    await this._refreshReport();
    return true;
  }

  Future<bool> _refreshReport() async {
    var tfs = TFSClient(this);
    await tfs.generateReporter();
    return true;
  }

  Future<bool> _refreshUser() async {
    var resp = await PATClient(this.userPAT)
        .get('${this.collectionUrl}/_api/_common/GetUserProfile')
        .timeout(Duration(seconds: 5));
    if (resp.statusCode != 200) throw 'status ${resp.statusCode}';
    var map = jsonDecode(resp.body);

    if (map['identity'] == null) {
      throw "获取用户信息失败";
    }
    this.userIdentify = map['identity'];
    print("用户信息 ${this.userIdentify}");
    return true;
  }

  AppData(
      {this.collectionUrl = 'http://edu.iseoo.com.cn:21000/tfsapi/tfs/DefaultCollection',
      this.projectName = 'iseoo_smartedu_v3'})
      : this._days = 7,
        this._reprter = '' {
    SharedPreferences.getInstance().then((pref) {
      this._userPAT = pref.getString('pat') ?? '';
      if (this._userPAT != '') {
        refresh();
      }
    });
  }
}
